package controllers;

import java.io.File;
import java.io.IOException;

import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.Kategori;
import models.Pesanan;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import system.Controller;

/**
 *
 * @author Rezan Achmad
 */
@WebServlet(name = "StatistikController", urlPatterns = {"/statistik", "/statistik/", "/statistik/index"})
public class StatistikController extends Controller {

    @Override
    protected void initRules() {
        rules.put("/statistik", identity.isManager() || identity.isAdmin());
        rules.put("/statistik/", identity.isManager() || identity.isAdmin());
        rules.put("/statistik/index", identity.isManager() || identity.isAdmin());
    }

    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userPath = request.getServletPath();

        if (userPath.equals("/statistik") || userPath.equals("/statistik/") || userPath.equals("/statistik/index")) {
            actionStatistic(request, response);
        } else {
            setView(userPath, request, response);
        }
    }

    private void actionStatistic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filePath = request.getServletContext().getRealPath("/") + "upload/" + "chart.jpg";
        //String chartPath = request.getServletContext() + "\\chart.jpg";

        System.out.println("filepath : " + filePath);

        //get all categories
        request.setAttribute("categories", Kategori.getAll());
        if (isGet) {
        } else if (isPost) {
            int status = Integer.parseInt(request.getParameter("delivery_status"));
            String startdate = request.getParameter("start_date");
            String enddate = request.getParameter("end_date");

            String sql = "";

            if (!(request.getParameter("category").equals(""))) {

                if (request.getParameter("category").equals("All")) {
                    sql = "SELECT * "
                            + "FROM `pesanan_item`,`pesanan`,`barang` "
                            + "WHERE (`pesanan_item`.`pesanan_id` = `pesanan`.`id`) ";
                    
                    if(status != 0) {
                        sql += "AND (`pesanan`.`status` = " + status + ") ";
                    }
                    
                    sql += "AND (`pesanan_item`.`barang_id` = `barang`.`id`) "
                    + "AND (`pesanan`.`tanggal` >= '" + startdate + "') "
                    + "AND (`pesanan`.`tanggal` <= '" + enddate + " 23:59:59') ";

                } else {
                    int categ_id = Integer.parseInt(request.getParameter("category"));
                    sql = "SELECT * "
                            + "FROM `pesanan_item`,`pesanan`,`barang` "
                            + "WHERE (`pesanan_item`.`pesanan_id` = `pesanan`.`id`) ";
                    
                    if(status != 0) {
                        sql += "AND (`pesanan`.`status` = " + status + ") ";
                    }
                    
                    sql += "AND (`pesanan_item`.`barang_id` = `barang`.`id`) "
                            + "AND (`barang`.`kategori_id` = " + categ_id + ")"
                            + "AND (`pesanan`.`tanggal` >= '" + startdate + "') "
                            + "AND (`pesanan`.`tanggal` <= '" + enddate + " 23:59:59') ";
                }

                Map result = Pesanan.getBySql(sql);
                if (result != null) {
                    request.setAttribute("result", result);
                    try {
                        if (generateChart(result, filePath)) {
                            request.setAttribute("chartPath", filePath);
                        }
                    } catch (Exception e) {
                        System.out.println("exception generate chart" + e.toString());
                        request.setAttribute("chartPath", null);
                    }
                } else {
                    System.out.println("result = null");
                    request.setAttribute("chartPath", null);
                }
                request.setAttribute("chosen_categ", request.getParameter("category"));
                request.setAttribute("chosen_status", status);
                request.setAttribute("startdate", startdate);
                request.setAttribute("enddate", enddate);
            }
        }

        // Set view
        setView("/statistik/statistik", request, response);
    }

    private boolean generateChart(Map<String, Integer> map, String sFilePath) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        if (map != null) {
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                dataset.setValue(entry.getValue(), "", entry.getKey());
            }
        } else {
            return false;
        }
        // Profit1, Profit2 represent the row keys
        // Jane, Tom, Jill, etc. represent the column keys
        JFreeChart chart = ChartFactory.createBarChart3D(
                "Data Penjualan Barang", // Chart name
                "Barang", // X axis label
                "Jumlah", // Y axis value
                dataset, // data set
                PlotOrientation.VERTICAL,
                false, true, false);
        // Creating a JPEG image
        try {
            ChartUtilities.saveChartAsJPEG(new File(sFilePath), chart, 500, 300);
            return true;
        } catch (IOException e) {
            System.err.println("Problem occurred creating chart." + e.toString());
            return false;
        }
    }
}
